#include "threadPool.h"

int exitPipe[2];

void handler(int signum)
{
    printf("receive exit signum(%d)\n", signum);
    write(exitPipe[1], "1", 1);
}

int main(int argc, char *argv[])
{
    /* ARGS_CHECK(argc, 4); */
    argv[1] = "127.0.0.1";
    argv[2] = "12345";
    argv[3] = "3";
    pipe(exitPipe);
    if(fork())
    {
        close(exitPipe[0]);
        signal(SIGUSR1, handler);
        wait(NULL);
        printf("main process exited.\n");
        exit(EXIT_SUCCESS);
    }
    close(exitPipe[1]);
    int workerNum = atoi(argv[3]);
    threadPool_t threadPool;
    threadPoolInit(&threadPool, workerNum);
    makeWorker(&threadPool); // create worker thread
    int sockfd = tcpInit(argv[1], argv[2]);
    int epfd = epoll_create(1);
    struct epoll_event readySet[1024];
    epollAdd(epfd, sockfd);
    epollAdd(epfd, exitPipe[0]);
    while(1)
    {
        int readyNum = epoll_wait(epfd, readySet, 1024, -1);
        for(int i = 0; i < readyNum; ++i)
        {
            if(readySet[i].data.fd == sockfd) // receive clien connection
            {
                int netfd = accept(sockfd, NULL, NULL);
                printf("1 clien has connected, netfd = %d\n", netfd);
                pthread_mutex_lock(&threadPool.mutex);
                enQueue(&threadPool.taskQueue, netfd);
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
            else if(readySet[i].data.fd == exitPipe[0]) // receive exit signal
            {
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);

                for(int j = 0; i < threadPool.workerInfo.workerNum; ++j)
                {
                    pthread_join(threadPool.workerInfo.workerArr[j], NULL);
                }
                printf("threadPool exit.\n");
                exit(EXIT_SUCCESS);
            }
        }
    }
    return 0;
}
